<template>
    <div class="main">
        <page-header-nav :content="pageTitle" :need-back="true" :need-underline="false"></page-header-nav>
        <div class="box">
            <div class="top">
                {{ `${note.formatDate}&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;${editor.inputCount}字` }}
                <div class="save btnFocus" @click="save">保存</div>
            </div>
            <div class="content">
                <div class="editor">
                    <Toolbar
                        style="border-bottom: 1px solid var(--grayColor)"
                        :editor="editor.editor"
                        :mode="editor.mode"
                    />
                    <Editor
                        v-model="editor.html"
                        :defaultConfig="editor.editorConfig"
                        :mode="editor.mode"
                        @onCreated="editorCreated"
                        @onChange="editorChange"
                    />
                </div>
            </div>
        </div>

    </div>
</template>

<script>
import PageHeaderNav from "@/components/Publlic/PageHeaderNav.vue"
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import serverConf from "@/utils/js/public/serverConf";

export default {
    components: {
        PageHeaderNav,
        Editor,
        Toolbar
    },

    data() {
        const _this = this
        return {
            pageTitle: "",

            // 富文本编辑器
            editor: {
                // 官方文档地址：https://www.wangeditor.com/v5/getting-started.html
                // 编辑器对象
                editor: null,
                // 填充在编辑器内的内容
                html: "",
                // 修改内容之前所包含的图片：用于保存时判断需要删除的图片
                beforeModifyImageVideoObjList: [],
                mode: 'simple',
                inputCount: 0,
                editorConfig: {
                    placeholder: '开始书写...',
                    MENU_CONF: {
                        uploadImage: {
                            // 选择文件时的类型限制
                            allowedFileTypes: ['image/*'],

                            // 上传图片
                            async customUpload(file, insertFn) {
                                // file 即选中的文件
                                // 自己实现上传，并得到图片 url alt href
                                // 最后插入图片
                                const max_size = 1024 * 1024

                                _this.$message({
                                    message: '正在上传...',
                                    type: 'success'
                                })

                                // 压缩图片
                                if (file.size > max_size) {
                                    file = await _this.$public.cutImage(file, max_size)
                                }

                                // 上传图片
                                let formData = new FormData()
                                formData.append("imageFile", file)

                                let url = await new Promise((resolve, reject) => {
                                    _this.request.post("/notes/uploadImage/", formData, {
                                        headers: {
                                            "Content-Type": "multipart/form-data",
                                        },
                                    }).then((response) => {
                                        const status = response["code"] === 200

                                        if (status) {
                                            resolve(response["data"]["url"])
                                        }
                                    }).catch(() => reject())
                                })

                                if (serverConf.DEBUG) url = serverConf.SERVER_URL + url
                                // 插入图片至富文本中
                                insertFn(url)
                            }
                        },

                        uploadVideo: {
                            // 选择文件时的类型限制
                            allowedFileTypes: ['video/*'],

                            // 上传视频
                            async customUpload(file, insertFn) {
                                // file 即选中的文件
                                // 自己实现上传，并得到视频 url alt href
                                // 最后插入视频
                                const max_size = 10 * 1024 * 1024

                                if (file.size > max_size) return _this.$message({
                                    message: '只能上传<10M的视频',
                                    type: 'warning'
                                })

                                _this.$message({
                                    message: '正在上传...',
                                    type: 'success'
                                })

                                // 上传视频
                                let formData = new FormData()
                                formData.append("videoFile", file)

                                let url = await new Promise((resolve, reject) => {
                                    _this.request.post("/notes/uploadVideo/", formData, {
                                        headers: {
                                            "Content-Type": "multipart/form-data",
                                        },
                                    }).then((response) => {
                                        const status = response["code"] === 200

                                        if (status) {
                                            resolve(response["data"]["url"])
                                        }
                                    }).catch(() => reject())
                                })

                                if (serverConf.DEBUG) url = serverConf.SERVER_URL + url
                                // 插入视频至富文本中
                                insertFn(url)
                            }
                        }
                    }
                }
            },

            // 备忘信息
            note: {
                id: null,
                content: null,
                formatDate: (() => {
                    const nowTimeStamp = this.$public.dateToTimeStampString(new Date())
                    return `${this.$public.formatTimeStampToYYMMDD(nowTimeStamp)} ${this.$public.formatTimeStampToHHmm(nowTimeStamp)}`
                })()
            }
        }
    },

    methods: {
        editorCreated(editor) {
            this.editor.editor = Object.seal(editor)
        },

        editorChange(editor) {
            this.editor.inputCount = editor.getText().length
            this.note.content = editor.getHtml()
            if (!this.editor.beforeModifyImageVideoObjList.length) this.editor.beforeModifyImageVideoObjList = [...this.editor.editor.getElemsByType('image'), ...this.editor.editor.getElemsByType('video')]
        },

        save() {
            const newImageVideoNameList = [...this.editor.editor.getElemsByType('image'), ...this.editor.editor.getElemsByType('video')].map(obj => obj.src.split("/").pop())
            const needRemoveImageVideoNameList = this.editor.beforeModifyImageVideoObjList.map(obj => obj.src.split("/").pop()).filter(name => !newImageVideoNameList.includes(name))

            this.$message({
                message: '正在保存...',
                type: 'success'
            })

            this.request.post("/notes/saveNote/", {
                id: this.note.id,
                content: this.note.content,
                timeStamp: this.$public.dateToTimeStampString(new Date()),
                needRemoveImageVideoNameList: needRemoveImageVideoNameList
            }).then((response) => {
                const status = response["code"] === 200

                if (status) {
                    setTimeout(() => {
                        this.$router.back()
                    }, 500)
                }
            })
        }
    },

    created() {
        // 路由地址切片，获取medicineId
        const routeList = this.$route.fullPath.split("/")
        const editNoteIndex = routeList.indexOf("editNoteView")

        // medicineId在路由结尾存在，请求指定药品的信息
        if (editNoteIndex < routeList.length - 1) {
            this.pageTitle = "修改备忘"
            const noteId = routeList[editNoteIndex + 1]

            this.$message({
                message: '努力加载中...',
                type: 'success'
            })

            this.request.post("/notes/getNote/", {
                id: noteId,
            }).then((response) => {
                const status = response["code"] === 200

                // 获取失败
                if (!status) {
                    setTimeout(() => {
                        this.$router.back()
                    }, 500)
                    return
                }

                // 获取成功，回写数据
                const note = response["data"]["note"]
                this.note.id = note.id
                this.note.content = note.content
                this.note.formatDate = `${this.$public.formatTimeStampToYYMMDD(note.timeStamp)} ${this.$public.formatTimeStampToHHmm(note.timeStamp)}`

                // 回写 数据到富文本框
                this.editor.html = this.note.content
            })
        } else {
            this.pageTitle = "新增备忘"
        }
    },

    beforeDestroy() {
        const editor = this.editor.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
}
</script>

<style lang="less" scoped>
@import "@wangeditor/editor/dist/css/style.css";

.main {
    width: 100%;
    height: 100%;
}

.box {
    width: 100%;
    height: calc(100% - 65px);
    box-sizing: border-box;
    padding: 15px 10px;
}

.top {
    margin: 0 0 30px 15px;
    font-weight: lighter;
    font-size: 0.9rem;

    .save {
        width: 2.5rem;
        height: 1.3rem;
        line-height: 1.3rem;
        text-align: center;
        color: white;
        border-radius: 5px;
        background-color: var(--color);
        float: right;
        margin-right: 15px;
        font-size: 0.8rem;
        font-weight: bold;
    }
}

.content {
    width: 100%;
    height: calc(100% - 30px - 15px);
    font-size: 1.1rem;

    .editor, .editor div:last-child {
        height: calc(100% - 100px);

        .w-e-text-container {
            height: 100%;

            .w-e-scroll {
                height: 100%;
            }
        }
    }
}
</style>